package com.csj.lc.service;

import cn.hutool.core.date.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class RedisComponent {
//
//    @Autowired
//    private RedisTemplate redisTemplate ;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 根据key获取String封装的value
    public String getString(String key){
        try{
            String value = stringRedisTemplate.opsForValue().get(key);
            return value;
        }catch(Exception ex){
            System.out.println("(Dickov)RedisComponent.getString EXCEPTION : " + ex);
            return null;
        }
    }

    // 根据Key删除redis数据
    public void removeKey(String key) {
        // 试过用redisTemplate删不掉！
        stringRedisTemplate.delete(key);
    }

    // 设值
    public void SetValue(String queryKey, int progress) {
        stringRedisTemplate.opsForValue().set(queryKey , progress+"");
    }

    // 往有序Set内添加数据
    public void addZSet( String zsetName, String value, double score ){

        score = (double)(DateTime.now().getTime());
        stringRedisTemplate.opsForZSet().add( zsetName , value , score ) ;

    }

    // 获取有序Set内的一个区间内的数据
    public Set<String>  getZset( String zsetName , long start , long stop){

        Set<String> result = (Set<String>)stringRedisTemplate.opsForZSet().range(zsetName, start ,stop );
        return result;
    }

    // 获取ZSet中是否存在某个键
    public boolean isZsetExists( String zsetName,String keyName){

        try{
            double score =  stringRedisTemplate.opsForZSet().score(zsetName,keyName);
//            System.out.println( "score = " + score );
            return true;
        }catch(Exception ex){
            return false;
        }
    }

    // 获取在线设备列表（此法应该弃用）
//    public Set<String>  getOnlineNameList(int pageNo) {
//
//        Set<String> olNameList = stringRedisTemplate.keys("DeviceOnline:*");
//        return olNameList ;
//    }
}
